<?php

/**
 * Created by PhpStorm.
 * User: wangjin
 * Date: 2017/9/4
 * Time: 下午1:53
 */
class BaseController extends Yaf_Controller_Abstract
{
    protected $twig = null;
    /**
     * init 初始化函数
     */
    protected function init()
    {
        $this->twig = Yaf_Registry::get('twig');
    }
    /**
     * 检查租售系统token
     * @param type $request_token
     * @return boolean
     * @throws Exception
     */
    public function check_token($request_token) {
	if (!empty($request_token)) {
	    $controller = $this->_request->controller;
	    $action = $this->_request->action;
	    $config = \Yaf_Registry::get('config');
	    $zushou_token_secret = $config->zushou_token_secret;
	    $str = $controller . $action . date("Y-m-d", time()) . $zushou_token_secret;
	    $token = md5(strtolower(trim($str)));
	    if ($request_token == $token) {
		return true;
	    } else {
		throw new Exception('token is wrong:' . $request_token, -1002);
		return FALSE;
	    }
	    exit;
	} else {
	    throw new Exception('token is  empty', -999);
	    return FALSE;
	}
    }
    

    /**
     * curl接收数据
     */
    public static function curl_receive() {
	$data = file_get_contents("php://input");
	if ($data == true) {
	    \Halo\Logger\Logger::info('curl_receive:' . $data);
	    return json_decode($data, true);
	} else {
	    return FALSE;
	}
    }

    /**
     * 发送邮件
     * @param type $data
     */
    public static function send_mail($data, $receive = array(), $title = '租售系统接口', $attachment = '') {
	if ($data == true) {
	    $mail = new Phpmailer();	    
	    //设置smtp参数 
	    $mail->IsSMTP();
	    $mail->SMTPAuth = true;
	    $mail->SMTPKeepAlive = true;
	    $mail->Host = "ssl://smtp.163.com";
	    $mail->Port = 465;
	    $mail->Username = 'zhouz10@163.com';
	    $mail->Password = 'zhouz10';
	    $mail->From = 'zhouz10@163.com';
	    $mail->FromName = 'zhouz10';
	    $mail->Subject = $title;
	    $mail->AltBody = $data;
	    $mail->WordWrap = 50;
	    $mail->MsgHTML($data);
	    foreach ($receive as $row) {
		$mail->AddAddress($row);
	    }
	    $mail->AddAttachment($attachment);
	    $mail->IsHTML(true);
	    if (!$mail->Send()) {
		//echo "Mailer Error:".$mail->ErrorInfo;
		echo "<meta charset=\"UTF-8\">";
		echo "<script language=\"JavaScript\">\r\n";
		echo " alert(\"对不起，邮件发送失败！！请充实\");\r\n";
		echo " history.back();\r\n";
		echo "</script>";
		exit;
		exit();
	    } else {
		echo "<meta charset=\"UTF-8\">";
		echo "<script language=\"JavaScript\">\r\n";
		echo " alert(\"发送成功！！\");\r\n";
		echo " history.back();\r\n";
		echo "</script>";
		exit;
	    }


	}
    }
}